@echo off
chcp 65001 >nul
cls

echo ==================================================
echo            MySQL远程连接问题修复工具              
echo ==================================================

:: 检查是否以管理员身份运行
net session >nul 2>&1
if %errorLevel% NEQ 0 (
    echo 请以管理员身份运行此批处理文件！
    pause
    exit /b 1
)

:: MySQL配置
set /p mysql_path=请输入MySQL安装路径 [默认: C:\Program Files\MySQL\MySQL Server 8.0\]: 
if "%mysql_path%"=="" set mysql_path=C:\Program Files\MySQL\MySQL Server 8.0\

set /p root_password=请输入MySQL root用户密码: 

:: 1. 检查并启动MySQL服务
echo [1/4] 检查MySQL服务状态...
sc query mysql | findstr "RUNNING"
if %errorLevel% EQU 0 (
    echo ✓ MySQL服务正在运行
) else (
    echo ✗ MySQL服务未运行，正在启动...
    net start mysql
    if %errorLevel% EQU 0 (
        echo ✓ MySQL服务已成功启动
    ) else (
        echo ✗ MySQL服务启动失败，请检查MySQL安装
        pause
        exit /b 1
    )
)

:: 2. 检查并修改MySQL配置文件
echo [2/4] 检查MySQL配置...
set config_file=%mysql_path%my.ini

:: 备份配置文件
copy "%config_file%" "%config_file%.bak.fix" >nul 2>&1

echo 正在修改bind-address...
(for /f "tokens=*" %%a in ('type "%config_file%"') do (
    echo %%a | findstr /c:"bind-address" >nul
    if errorlevel 1 (
        echo %%a
    ) else (
        echo bind-address = 0.0.0.0
    )
)) > "%config_file%.tmp"
move /y "%config_file%.tmp" "%config_file%" >nul 2>&1
echo ✓ MySQL配置已更新，bind-address已设置为0.0.0.0

:: 3. 检查并配置防火墙规则
echo [3/4] 检查防火墙规则...
netsh advfirewall firewall show rule name="MySQL" >nul 2>&1
if %errorLevel% EQU 0 (
    echo ✓ 防火墙规则已存在
) else (
    echo ✗ 防火墙规则不存在，正在添加...
    netsh advfirewall firewall add rule name="MySQL" dir=in action=allow protocol=TCP localport=3306 >nul 2>&1
    netsh advfirewall firewall add rule name="MySQL" dir=out action=allow protocol=TCP localport=3306 >nul 2>&1
    echo ✓ 防火墙规则已添加
)

:: 4. 重启MySQL服务
echo [4/4] 重启MySQL服务...
net stop mysql >nul 2>&1
net start mysql >nul 2>&1
echo ✓ MySQL服务已重启

:: 显示本机IP地址
echo.
echo 获取本机IP地址...
ipconfig | findstr /i "IPv4"

echo.
echo ==================================================
echo                   修复完成                        
echo ==================================================
echo 连接信息：
echo 主机: 上面显示的IPv4地址
echo 端口: 3306
echo 用户名: remote_user
echo 密码: remote_password123
echo 数据库: community_service_platform
echo ==================================================

pause